package com.pie4cloud.pie.dmz.handler;


import com.pie4cloud.pie.dmz.entty.constant.ConstantValue;
import com.pie4cloud.pie.dmz.entty.enums.MsgTypeEnum;
import com.pie4cloud.pie.dmz.entty.netty.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.CharsetUtil;

import java.util.List;

public class MsgDecoder extends ByteToMessageDecoder {

	//消息头部长度
	private static final int BASE_LENGTH = 4 + 4 + 32 + 4 + 4;

	@Override
	protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
		if (byteBuf.readableBytes() >= BASE_LENGTH) {
			Message message = new Message();
			int beginReader;
			while (true) {
				beginReader = byteBuf.readerIndex();
				byteBuf.markReaderIndex();
				if (byteBuf.readInt() == ConstantValue.MSG_HEAD) {
					break;
				}
				byteBuf.resetReaderIndex();
				byteBuf.readByte();
				if (byteBuf.readableBytes() < BASE_LENGTH) {
					return;
				}
			}
			int sessionLength = byteBuf.readInt();

			CharSequence charSequence = byteBuf.readCharSequence(sessionLength, CharsetUtil.UTF_8);
			String sessionId = (String) charSequence;
			message.setSessionId(sessionId);
			int msgType = byteBuf.readInt();
			MsgTypeEnum msgTypeEnum = MsgTypeEnum.get(msgType);
			message.setMsgTypeEnum(msgTypeEnum);

			int bodyLength = byteBuf.readInt();

			if (bodyLength == 0) {
				message.setMsgBody(null);
				byteBuf.discardReadBytes();
				list.add(message);
			} else {
				if (byteBuf.readableBytes() >= bodyLength) {
					byte[] bytes = new byte[bodyLength];
					byteBuf.readBytes(bytes);
//                    System.out.println(String.format("write: ridx=%s widx=%s cap=%s", byteBuf.readerIndex(), byteBuf.writerIndex(), byteBuf.capacity()));
					message.setMsgBody(bytes);
					list.add(message);
				} else {
					byteBuf.readerIndex(beginReader);
				}
			}
		}
	}
}
